import UIKit

enum SortState {
  case none
  case ascending
  case descending
}

class SortButton: UIButton {

  private(set) var sortState: SortState = .none {
    didSet {
      updateAppearance()
    }
  }

  weak var manager: SortButtonManager?  // 管理器，弱引用，避免循环引用

  var onSortChanged: ((SortState) -> Void)?

  private let upArrow = UIImage(named: "icon_sort_up")
  private let downArrow = UIImage(named: "icon_sort_down")
  private let noneArrow = UIImage(named: "icon_sort_default")  // 默认双箭头

  override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
  }

  required init?(coder: NSCoder) {
    super.init(coder: coder)
    setup()
  }

  private func setup() {
    addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
    setTitleColor(.black, for: .normal)
    titleLabel?.font = UIFont.systemFont(ofSize: 14)
    updateAppearance()
  }

  @objc private func buttonTapped() {
    manager?.buttonTapped(self)
  }

  func cycleSortOrder() {
    switch sortState {
    case .none:
      sortState = .ascending
    case .ascending:
      sortState = .descending
    case .descending:
      sortState = .none
    }

    // 回调给外面，告诉当前是哪个排序状态
    onSortChanged?(sortState)
  }

  func resetToDefault() {
    sortState = .none
  }

  private func updateAppearance() {
    var image: UIImage?

    switch sortState {
    case .none:
      image = noneArrow
    case .ascending:
      image = upArrow
    case .descending:
      image = downArrow
    }
    setImage(image, for: .normal)
    semanticContentAttribute = .forceRightToLeft

  }
}

extension SortButton: SelectableButton {
  func onTapped() {
    cycleSortOrder()
  }
}
